# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSMaintenancePlanTemplate(Document):
	def before_insert(self):
		part_items = self.get_maintenance_item_parts()
		for row in part_items:
			self.append("part_items", row)


	# 根据items行记录中replacement_part==1的条件去获取配件
	@frappe.whitelist()
	def get_maintenance_item_parts(self):
		part_items = []
		for i in self.items:
			if i.replacement_part == 1:
				maintenance_item = frappe.get_doc('EMS Maintenance Item', i.maintenance_item)
				for row in maintenance_item.items:
					part_items.append({'item_code': row.item_code, 'qty': row.qty})
		return part_items

	# 手动执行: 根据items行记录中replacement_part==1的条件去获取配件并填充
	@frappe.whitelist()
	def append_part_items(self):
		self.part_items = []
		part_items = self.get_maintenance_item_parts()
		for row in part_items:
			self.append("part_items", row)
		self.save()
		self.reload()